package app.ui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFrame;

import app.action.AppUtilities;

/**
 * Create class named: <b>MainFrame</b> extending this class for your application
 * 
 * @author manh.vu
 */
public abstract class AbsMainFrame extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6655104925579046422L;
	private final static Logger LOG = Logger.getLogger(AbsMainFrame.class.getName());

	protected GridBagConstraints constraints;
	protected AppUtilities appUtilities;

	public AbsMainFrame(AppUtilities appUtilities) {
		super("Main Frame");

		this.appUtilities = appUtilities;
		this.getContentPane().setLayout(new GridBagLayout());
		this.addWindowListener(new WindowAction());
		this.constraints = new GridBagConstraints();
		constraints.fill = GridBagConstraints.BOTH;
		constraints.weightx = 1;
		constraints.weighty = 1;

		setDefaultCloseOperation(EXIT_ON_CLOSE);

		Dimension size = new Dimension(800, 600);
		setSize(size);
		setMinimumSize(size);
		setLocation(280, 120);

		initialize();
	}

	/**
	 * Commonly add components here
	 */
	public abstract void initialize();

	@Override
	public Component add(Component comp) {
		if(comp instanceof AbsCommonPanel) {
			AbsCommonPanel mPanel = (AbsCommonPanel) comp;
			mPanel.makeThisAutoResize();
			this.getContentPane().add(comp, getConstraints());
			return comp;
		}

		return super.add(comp);
	}

	public GridBagConstraints getConstraints() {
		return constraints;
	}

	public AppUtilities getAppUtilities() {
		return appUtilities;
	}

	public void savingStatusBeforClosing() {
		try {
			appUtilities.storingPropertiesFile();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void closing() {
		applicationIsGoingToShutdown();
		LOG.log(Level.OFF, "System exit!", this);
		this.savingStatusBeforClosing();
		System.exit(0);
	}

	/**
	 * This function will handle any essential task need to do <br>
	 * before application shutdown
	 */
	public abstract void applicationIsGoingToShutdown();
}

class WindowAction extends WindowAdapter {

	@Override
	public void windowClosing(WindowEvent e) {
		AbsMainFrame mFrame = (AbsMainFrame) e.getSource();
		mFrame.applicationIsGoingToShutdown();
		mFrame.savingStatusBeforClosing();
		super.windowClosing(e);
	}

}
